package com.cxyd.modules.wcs.service.impl;

import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.cxyd.common.constant.WcsConstants;
import com.cxyd.common.service.impl.CrudServiceImpl;
import com.cxyd.common.utils.ApiResult;
import com.cxyd.common.utils.ConvertUtils;
import com.cxyd.modules.api.dto.DvcStateDTO;
import com.cxyd.modules.log.service.SysLogWorkService;
import com.cxyd.modules.wcs.dao.StnMappingDao;
import com.cxyd.modules.wcs.dto.StnMappingDTO;
import com.cxyd.modules.wcs.entity.PcItemEntity;
import com.cxyd.modules.wcs.entity.StnMappingEntity;
import com.cxyd.modules.wcs.entity.StockEntity;
import com.cxyd.modules.wcs.service.PcItemService;
import com.cxyd.modules.wcs.service.StnMappingService;
import org.apache.commons.lang3.ObjectUtils;
import org.apache.commons.lang3.StringUtils;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import javax.annotation.Resource;
import java.util.Date;
import java.util.Map;

@Service
public class StnMappingServiceImpl extends CrudServiceImpl<StnMappingDao, StnMappingEntity, StnMappingDTO> implements StnMappingService {
    @Resource
    private SysLogWorkService logWorkService;
    @Resource
    private PcItemService pcItemService;

    @Override
    public QueryWrapper<StnMappingEntity> getWrapper(Map<String, Object> params) {
        String wcsStation = (String) params.get("wcsStation");
        String status = (String) params.get("status");
        String contNo = (String) params.get("contNo");
        String stationType = (String) params.get("stationType");
        final QueryWrapper<StnMappingEntity> wrapper = new QueryWrapper<>();
        wrapper.isNotNull("wms_station");
        wrapper.like(StringUtils.isNotBlank(wcsStation), "wcs_station", wcsStation);
        wrapper.eq(StringUtils.isNotBlank(status), "status", status);
        wrapper.like(StringUtils.isNotBlank(contNo), "cont_no", contNo);
        wrapper.like(StringUtils.isNotBlank(stationType), "station_type", stationType);
        return wrapper;
    }

    /**
     * 人为变更站点状态（需要做记录）
     *
     * @param dto
     */
    @Override
    public void update(StnMappingDTO dto) {
        String workName = "站点信息变更-人工";
        String workProc = "StnMappingServiceImpl.update";
        String workCode = "0";
        String workMsg = "站点：[" + dto.getWmsStation() + "]状态变更为" + dto.getStatus() + "满料[" + dto.getIsFull() + "]";
        StnMappingEntity entity = ConvertUtils.sourceToTarget(dto, StnMappingEntity.class);
//        if (StringUtils.isNotBlank(dto.getContType()) || StringUtils.isNotBlank(dto.getIsFull())) {
//            entity.setStatus(2);
//        } else {
//            entity.setStatus(0);
//        }
        entity.setStatus(dto.getStatus());
        entity.setUpdateDate(new Date());
        baseDao.updateById(entity);

        logWorkService.workLogging(workName, entity.getWmsStation(), workCode, workMsg, "", workProc, WcsConstants.WCS_USER_NAME, 3L);
    }

    @Override
    public ApiResult updateStateByStation(DvcStateDTO dto) {
        if (StringUtils.isBlank(dto.getMapCode())) {
            return new ApiResult().feedBack("更新站点不能为空", dto.getRequestPk());
        }
        String workName = "站点状态更新-MES";
        String workProc = "StnMappingServiceImpl.updateStateByStation";
        String workCode = "0";
        String workMsg = "站点：[" + dto.getMapCode() + "]状态由MES变更为[" + dto.getStatus() + "]Type[" + dto.getContType() + "]是否满料[" + dto.getIsFull() + "]";
//        匹配站点在mcs是否存在
        QueryWrapper<StnMappingEntity> qw = new QueryWrapper<>();
        qw.eq("wms_station", dto.getMapCode());
        StnMappingEntity stnEntity = baseDao.selectOne(qw);
        if (stnEntity == null) {
            workCode = "update_error_001";
            workMsg = "站点：[" + dto.getMapCode() + "]在MCS未配置!";
            logWorkService.workLogging(workName, dto.getMapCode(), workCode, workMsg, "", workProc, WcsConstants.WCS_USER_NAME, 3L);
            return new ApiResult().feedBack(workMsg, dto.getRequestPk());
        }
//        更新站点状态(状态=2则填充contNo)
        if ("true".equals(dto.getStatus())) {
            stnEntity.setComments(dto.getRequestPk());
            stnEntity.setStatus(2);
            stnEntity.setContType(dto.getContType());
            stnEntity.setIsFull(dto.getIsFull());
        } else {
            stnEntity.setStatus(0);
            stnEntity.setContNo("");
            stnEntity.setContType("");
            stnEntity.setIsFull("");
        }
        baseDao.updateById(stnEntity);
        logWorkService.workLogging(workName, dto.getMapCode(), "0", workMsg, "", workProc, WcsConstants.WCS_USER_NAME, 3L);
        return new ApiResult().feedBack(dto.getRequestPk());
    }

    @Override
    public StnMappingEntity getStnByNo(String wcsStation) {
        QueryWrapper<StnMappingEntity> qw = new QueryWrapper<>();
        qw.eq("wcs_station", wcsStation);
        return baseDao.selectOne(qw);
    }

    @Override
    public StnMappingEntity getUsableStnByNo(String wmsStation, int status) {
        QueryWrapper<StnMappingEntity> qw = new QueryWrapper<>();
        qw.eq("wms_station", wmsStation)
                .eq("status", status).last("limit 1");
        return baseDao.selectOne(qw);
    }

    @Override
    public StnMappingEntity getUsableStnByType(String contType, String isFull) {
        QueryWrapper<StnMappingEntity> qw = new QueryWrapper<>();
        qw.eq("cont_type", contType)
                .eq("is_full", isFull)
                .eq("station_type", "HW")
                .eq("status", 2).last("limit 1");
        return baseDao.selectOne(qw);
    }

    @Override
    @Transactional(rollbackFor = Exception.class)
    public void updateStnMapping(StnMappingDTO dto) {
        //删除或添加货位信息时，需通知plc 0-修改为无货 2-修改为有货
        PcItemEntity pcItemByStn = pcItemService.getPcItemByStn(dto.getWcsStation(), "PC_STATUS");
        if (dto.getStatus() == 0) {
            pcItemService.updateValueByNo(pcItemByStn.getItemNo(),"0");
        } else {
            pcItemService.updateValueByNo(pcItemByStn.getItemNo(),"1");
        }
        dto.setUpdateDate(new Date());
        dto.setComments("人工修改库存");
        this.update(dto);
    }
}
